/*
 * @Author: 曹捷
 * @Date: 2020-07-22 14:55:59
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-03-02 15:25:22
 * @Description: 系统通用方法
 */
class app {
  /**
   * 系统统一跳转接口，记录浏览地址重定向等操作
   * url有长度限制，太长的字符串会传递失败 encodeURIComponent编码和解码
   * @param {*} url
   * 跳转的地址
   * @param {*} params
   * 额外添加的参数对象
   */
  goto (url, params, isStorage = true) {
    let chart = url.indexOf('?') !== -1 ? '&' : '?'
    let toUrl = `${url}`
    if (params) {
      toUrl += `${chart}params=${encodeURIComponent(JSON.stringify(params))}`
    }
    /**
     * encodeURI的参数，必须解码储存，否则会导致多重编码，解析失败
     */
    if (isStorage) {
      let fullPath = decodeURI(toUrl)
      let param = { url: `${fullPath}` }
      uni.setStorageSync('pager', param)
    }
    if (url.indexOf('tabbar') !== -1) {
      uni.switchTab({
        url: toUrl,
        fail: function () {
          uni.navigateTo({ url: toUrl })
        },
      })
    } else {
      uni.navigateTo({
        url: toUrl,
        fail: function () {
          uni.switchTab({ url: toUrl })
        },
      })
    }
  }
  to (toUrl, params) {
    this.goto(toUrl, params, false)
  }
  redirectTo (url, params) {
    console.log('🚀 ~ file: app.js ~ line 46 ~ redirectTo ~ url', url)
    let chart = url.indexOf('?') !== -1 ? '&' : '?'
    let toUrl = `${url}`
    if (params) {
      toUrl += `${chart}params=${encodeURIComponent(JSON.stringify(params))}`
    }
    uni.redirectTo({
      url: toUrl,
    });
  }
  reLaunch (url, params) {
    let chart = url.indexOf('?') !== -1 ? '&' : '?'
    let toUrl = `${url}`
    if (params) {
      toUrl += `${chart}params=${encodeURIComponent(JSON.stringify(params))}`
    }
    uni.reLaunch({
      url: toUrl,
    });
  }
  convertUrl (baseUrl, queryConfig) { //吧对象转为url字符拼接
    var _str = "";
    for (var o in queryConfig) {
      if (queryConfig[o] != -1) {
        _str += o + "=" + queryConfig[o] + "&";
      }
    }
    var _str = _str.substring(0, _str.length - 1);
    if (baseUrl) {
      let icon = baseUrl.indexOf('?') !== -1 ? '&' : '?'
      return `${baseUrl}${icon}${_str}`
    }
    return _str;
  }
  goback (url) {
    let pages = getCurrentPages()
    console.log('🚀 ~ file: app.js ~ line 87 ~ goback ~ pages', pages)
    if (url) {
      if (pages.length > 1) {
        let route = pages[pages.length - 2].__page__.path
        if (route.indexOf(url) !== -1) {
          uni.navigateBack()
        } else {
          this.reLaunch(url)
        }
      } else {
        this.redirectTo(url)
      }
    } else {
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        history.back()
      }
    }

  }
  close () {
    window.opener = null
    window.open('about:blank', '_top').close()
  }
  call (moblie) {
    uni.makePhoneCall({
      phoneNumber: moblie
    });
  }
  setTitle (title) {
    uni.setNavigationBarTitle({
      title
    });
  }
  // URL 解析数据
  getUrlParams (option) {
    if (option.params) {
      let result
      try {
        result = JSON.parse(decodeURIComponent(option.params.replace(/%/g, '%25')))
      } catch (error) {
        result = JSON.parse(decodeURIComponent(option.params))
      }

      delete option.params
      return Object.assign(option, result)
    } else {
      return option
    }
  }
  /**
   * 通用跳转图片查看详情页面
   * @param {*} index 当前图片下标位置
   * @param {*} list 图片集合
   * @param {*} fileUrl 要展示的图片字段key
   */
  toshowImg (index, list, params = '', fileUrl = 'fileUrl') {
    uni.setStorageSync('photo_look', list)
    uni.navigateTo({
      url: `/app-modules/pages/photo/photoShow?index=${index}&img=${fileUrl}${params}`,
    })
  }
  /**
   * 跳转用户个人中心
   * @param {*} id 用户userID
   * @param {*} name 用户userName
   */
  toUserCenter (id, name) {
    uni.navigateTo({
      url: `/pages/center/center/center?name=${name}&id=${id}`,
    })
  }
  getUserInfo () {
    return uni.getStorageSync('userInfo')
  }
  setCopy (info = '复制数据', tips = '复制成功') {
    uni.setClipboardData({
      data: info,
      success: function () {
        uni.showToast({
          title: tips,
          icon: 'none',
        })
      },
    })
  }
  cachInfo (key) {
    class cachInfo {
      constructor (key) {
        this.key = key
        this.dataInfo = this.get()
      }
      get () {
        return uni.getStorageSync(this.key)
      }
      set (data) {
        uni.setStorageSync(this.key, data)
        this.dataInfo = data
      }
      remove () {
        uni.removeStorageSync(this.key)
        this.dataInfo = null
      }
    }
    return new cachInfo(key)
  }
  /**
 * 设置系统剪贴板的内容
 * @param {string} data 需要设置的内容
 * @returns {Promise} 设置状态
 */
  setClipboardData (data) {
    return new Promise((success, fail) => {
      // #ifndef H5
      uni.setClipboardData({ data, success, fail });
      // #endif

      // #ifdef H5
      // navigator.clipboard.writeText(data).then(success).catch(fail);
      const textarea = document.createElement('textarea');
      textarea.value = data;
      textarea.readOnly = 'readOnly';
      document.body.appendChild(textarea);
      textarea.select();
      textarea.setSelectionRange(0, data.length);
      document.execCommand('copy');
      textarea.remove();
      success(data);
      // #endif
    });
  }

  /**
 * 获取系统剪贴板内容
 * @returns {Promise} 剪贴板内容
 */
  getClipboardData () {
    return new Promise((success, fail) => {
      // #ifndef H5
      uni.getClipboardData({ success, fail });
      // #endif

      // #ifdef H5
      navigator.clipboard.readText().then(success).catch(fail);
      // #endif
    });
  }

}
export default new app()
